package com.atguigu.prototype.deepclone;

import lombok.*;

import java.io.*;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class DeepProtoType implements Serializable, Cloneable {
    private String name;
    private DeepCloneableTarget deepCloneableTarget;

    @Override
    protected Object clone() throws CloneNotSupportedException {

        Object deep = super.clone();

        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.setDeepCloneableTarget((DeepCloneableTarget) deepCloneableTarget.clone());

        return deepProtoType;
    }

    public Object deepClone() {
        ByteArrayOutputStream bos = null;

        try (ObjectOutputStream oos = new ObjectOutputStream(bos = new ByteArrayOutputStream())) {
            oos.writeObject(this);
            oos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
